<template>
  <div class="admin-container">
    <div class="page-header">
      <h2>用户管理</h2>
    </div>

    <el-card>
      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="用户名">
            <el-input v-model="searchForm.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="searchForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="用户角色">
            <el-select v-model="searchForm.role" placeholder="全部角色">
              <el-option label="全部角色" value="" />
              <el-option label="普通用户" value="user" />
              <el-option label="卖家" value="seller" />
              <el-option label="管理员" value="admin" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 用户列表 -->
      <el-table
        v-loading="isLoading"
        :data="filteredUsers"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="用户ID" width="80" />
        <el-table-column prop="username" label="用户名" width="150">
          <template #default="scope">
            <div class="user-info">
              <img :src="scope.row.avatar || '/images/default-avatar.png'" alt="头像" class="avatar">
              <span>{{ scope.row.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="role" label="角色" width="120">
          <template #default="scope">
            <el-tag :type="getRoleType(scope.row.role)">
              {{ getRoleText(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" text @click="editUser(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" text @click="deleteUser(scope.row.id)">
              删除
            </el-button>
            <el-button v-if="scope.row.role !== 'admin'" text @click="setAdmin(scope.row.id)">
              设为管理员
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedUsers.length > 0">
        <span>已选择 {{ selectedUsers.length }} 项</span>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
        <el-button type="primary" @click="batchEnable">批量启用</el-button>
        <el-button type="warning" @click="batchDisable">批量禁用</el-button>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑用户弹窗 -->
    <el-dialog v-model="showEditDialog" title="编辑用户" width="600px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="用户角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色">
            <el-option label="普通用户" value="user" />
            <el-option label="卖家" value="seller" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户状态">
          <el-switch
            v-model="editForm.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="saveUser">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../../store'

const userStore = useUserStore()
const isLoading = ref(false)
const selectedUsers = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const showEditDialog = ref(false)
const editFormRef = ref(null)

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  role: ''
})

// 编辑表单
const editForm = reactive({
  id: '',
  username: '',
  email: '',
  phone: '',
  role: '',
  status: 1
})

// 编辑表单验证规则
const editRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  role: [{ required: true, message: '请选择用户角色', trigger: 'change' }]
}

// 模拟用户数据
const users = ref([
  {
    id: 1,
    username: 'admin',
    email: 'admin@example.com',
    phone: '13800138000',
    password: 'hashed_password',
    avatar: '/images/admin-avatar.png',
    role: 'admin',
    status: 1,
    createdAt: '2023-01-01 00:00:00'
  },
  {
    id: 2,
    username: 'zhangsan',
    email: 'zhangsan@example.com',
    phone: '13900139000',
    password: 'hashed_password',
    avatar: '/images/user1-avatar.png',
    role: 'seller',
    status: 1,
    createdAt: '2023-02-15 10:30:00'
  },
  {
    id: 3,
    username: 'lisi',
    email: 'lisi@example.com',
    phone: '13700137000',
    password: 'hashed_password',
    avatar: '',
    role: 'user',
    status: 1,
    createdAt: '2023-03-20 15:45:00'
  },
  {
    id: 4,
    username: 'wangwu',
    email: 'wangwu@example.com',
    phone: '13600136000',
    password: 'hashed_password',
    avatar: '/images/user2-avatar.png',
    role: 'user',
    status: 0,
    createdAt: '2023-04-10 09:20:00'
  },
  {
    id: 5,
    username: 'zhaoliu',
    email: 'zhaoliu@example.com',
    phone: '13500135000',
    password: 'hashed_password',
    avatar: '/images/user3-avatar.png',
    role: 'seller',
    status: 1,
    createdAt: '2023-05-05 16:10:00'
  }
])

onMounted(() => {
  loadUsers()
})

const loadUsers = async () => {
  isLoading.value = true
  
  try {
    // 在实际项目中，这里应该从API获取用户数据
    // await userStore.fetchUsers()
    
    // 模拟数据加载延迟
    await new Promise(resolve => setTimeout(resolve, 500))
  } catch (error) {
    ElMessage.error('加载用户数据失败，请稍后重试')
    console.error('加载用户数据失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 根据搜索条件过滤用户
const filteredUsers = computed(() => {
  let result = [...users.value]
  
  if (searchForm.username) {
    result = result.filter(user => 
      user.username.toLowerCase().includes(searchForm.username.toLowerCase())
    )
  }
  
  if (searchForm.email) {
    result = result.filter(user => 
      user.email.toLowerCase().includes(searchForm.email.toLowerCase())
    )
  }
  
  if (searchForm.role) {
    result = result.filter(user => user.role === searchForm.role)
  }
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  
  return result.slice(start, end)
})

// 总用户数
const total = computed(() => {
  let result = [...users.value]
  
  if (searchForm.username) {
    result = result.filter(user => 
      user.username.toLowerCase().includes(searchForm.username.toLowerCase())
    )
  }
  
  if (searchForm.email) {
    result = result.filter(user => 
      user.email.toLowerCase().includes(searchForm.email.toLowerCase())
    )
  }
  
  if (searchForm.role) {
    result = result.filter(user => user.role === searchForm.role)
  }
  
  return result.length
})

const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置为第一页
}

const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
}

const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

const getRoleText = (role) => {
  const roleMap = {
    user: '普通用户',
    seller: '卖家',
    admin: '管理员'
  }
  return roleMap[role] || '未知角色'
}

const getRoleType = (role) => {
  const typeMap = {
    user: 'info',
    seller: 'warning',
    admin: 'success'
  }
  return typeMap[role] || 'default'
}

const handleStatusChange = async (user) => {
  try {
    // 在实际项目中，这里应该调用API更新用户状态
    const statusText = user.status === 1 ? '启用' : '禁用'
    ElMessage.success(`用户 ${statusText} 成功`)
  } catch (error) {
    // 发生错误时恢复原状态
    user.status = user.status === 1 ? 0 : 1
    ElMessage.error(`用户 ${user.status === 1 ? '启用' : '禁用'} 失败，请稍后重试`)
  }
}

const editUser = (user) => {
  // 填充编辑表单
  Object.assign(editForm, user)
  showEditDialog.value = true
}

const saveUser = async () => {
  await editFormRef.value.validate()
  
  try {
    // 在实际项目中，这里应该调用API更新用户信息
    const index = users.value.findIndex(u => u.id === editForm.id)
    if (index !== -1) {
      users.value[index] = { ...users.value[index], ...editForm }
    }
    
    showEditDialog.value = false
    ElMessage.success('用户信息更新成功')
  } catch (error) {
    ElMessage.error('更新用户信息失败，请稍后重试')
    console.error('更新用户信息失败:', error)
  }
}

const deleteUser = async (userId) => {
  const user = users.value.find(u => u.id === userId)
  if (user && user.role === 'admin') {
    ElMessage.warning('不能删除管理员账号')
    return
  }
  
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？删除后不可恢复', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger'
    })
    
    // 在实际项目中，这里应该调用API删除用户
    const index = users.value.findIndex(u => u.id === userId)
    if (index !== -1) {
      users.value.splice(index, 1)
    }
    
    ElMessage.success('用户删除成功')
  } catch (error) {
    // 用户取消操作，不做任何处理
  }
}

const setAdmin = async (userId) => {
  try {
    await ElMessageBox.confirm('确定要将该用户设置为管理员吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 在实际项目中，这里应该调用API设置用户角色
    const index = users.value.findIndex(u => u.id === userId)
    if (index !== -1) {
      users.value[index].role = 'admin'
    }
    
    ElMessage.success('设置成功')
  } catch (error) {
    // 用户取消操作，不做任何处理
  }
}

const batchDelete = async () => {
  // 检查是否包含管理员
  const hasAdmin = selectedUsers.value.some(user => user.role === 'admin')
  if (hasAdmin) {
    ElMessage.warning('不能批量删除管理员账号')
    return
  }
  
  try {
    await ElMessageBox.confirm('确定要删除选中的用户吗？删除后不可恢复', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger'
    })
    
    // 在实际项目中，这里应该调用API批量删除用户
    const ids = selectedUsers.value.map(user => user.id)
    users.value = users.value.filter(user => !ids.includes(user.id))
    
    selectedUsers.value = [] // 清空选中状态
    ElMessage.success(`成功删除 ${ids.length} 个用户`)
  } catch (error) {
    // 用户取消操作，不做任何处理
  }
}

const batchEnable = async () => {
  try {
    // 在实际项目中，这里应该调用API批量启用用户
    const ids = selectedUsers.value.map(user => user.id)
    users.value.forEach(user => {
      if (ids.includes(user.id)) {
        user.status = 1
      }
    })
    
    selectedUsers.value = [] // 清空选中状态
    ElMessage.success(`成功启用 ${ids.length} 个用户`)
  } catch (error) {
    ElMessage.error('批量启用失败，请稍后重试')
  }
}

const batchDisable = async () => {
  // 检查是否包含管理员
  const hasAdmin = selectedUsers.value.some(user => user.role === 'admin')
  if (hasAdmin) {
    ElMessage.warning('不能禁用管理员账号')
    return
  }
  
  try {
    // 在实际项目中，这里应该调用API批量禁用用户
    const ids = selectedUsers.value.map(user => user.id)
    users.value.forEach(user => {
      if (ids.includes(user.id)) {
        user.status = 0
      }
    })
    
    selectedUsers.value = [] // 清空选中状态
    ElMessage.success(`成功禁用 ${ids.length} 个用户`)
  } catch (error) {
    ElMessage.error('批量禁用失败，请稍后重试')
  }
}
</script>

<style scoped>
.admin-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  font-size: 24px;
  color: #333;
}

.search-section {
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.batch-actions {
  margin-top: 20px;
  padding: 15px;
  background: #fafafa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .search-form {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }
  
  .batch-actions {
    flex-wrap: wrap;
  }
  
  .pagination-container {
    justify-content: center;
  }
}
</style>